<template>
  <scroll-view scroll-y="ture" style="height: 100vh">
    <template v-if="activityStatus === '活动中'">
      <view
        class="panda-container"
        :style="{
          backgroundImage: `url(${oss2('others/panda2023/index_bg.png')})`,
        }"
      >
        <view
          class="my"
          :style="{
            backgroundImage: `url(${oss2('others/panda2023/but_list.png')})`,
          }"
          @click.stop="toMy"
        ></view>

        <view
          class="rule"
          @click.stop="openRule"
          :style="{
            backgroundImage: `url(${oss2(
              'others/panda2023/button_explain.png'
            )})`,
          }"
        ></view>

        <view
          class="desire"
          @click.stop="toDesire"
          :style="{
            backgroundImage: `url(${oss2(
              'others/panda2023/button_desire.png'
            )})`,
          }"
        ></view>

        <view
          class="wishGranter"
          @click.stop="toScanCode"
          :style="{
            backgroundImage: `url(${oss2('others/panda2023/button_xy.png')})`,
          }"
        ></view>
        <view class="prize_and_story">
          <view
            class="prize"
            :style="{
              backgroundImage: `url(${oss2('others/panda2023/pic_gf.png')})`,
            }"
            ><view
              class="prize_btn"
              @click="toPrize"
              :style="{
                backgroundImage: `url(${oss2('others/panda2023/gf.png')})`,
              }"
            ></view>
          </view>
          <view
            class="story"
            :style="{
              backgroundImage: `url(${oss2('others/panda2023/pic_pt.png')})`,
            }"
            ><view
              class="story_btn"
              @click.stop="toStory"
              :style="{
                backgroundImage: `url(${oss2('others/panda2023/pt.png')})`,
              }"
            ></view
          ></view>
        </view>

        <view class="agree">
          <view class="flex items-center justify-center">
            <template>
              <image
                v-if="iAgree"
                class="i-agree"
                :src="ossImg('others/panda2023/choose.png')"
                @click.stop="doAgree"
              />
              <view v-else class="i-agree" @click.stop="doAgree"> </view>
            </template>
            <view class="agree-content">
              已阅读并同意
              <view class="link" @click.stop="openRule2">活动规则</view>
            </view>
          </view>
        </view>
      </view>
    </template>
    <template v-else>
      <view
        class="panda-container puzzle"
        :style="{
          backgroundImage: `url(${
            activityStatus === '未开始'
              ? oss2('others/panda2023/NotStarted_pic.png')
              : activityStatus === '已结束'
              ? oss2('others/panda2023/puzzle_js.png')
              : oss2('others/panda2023/puzzle_fm.png')
          })`,
        }"
      >
        <view
          class="backHomeBtn"
          @click.stop="backHome"
          :style="{
            backgroundImage: `url(${oss2('others/panda2023/Button_back.png')})`,
          }"
        ></view>
      </view>
    </template>

    <!-- 弹窗2 -->
    <view class="mode" v-if="showDialog2">
      <view
        class="Dialog_body w-306px h-233px top-204px left-34.5px"
        :style="{
          backgroundImage: `url(${oss2('others/panda2023/tk_bg2.png')})`,
        }"
        ><view
          class="Dialog_back w-119px h-44.5px bottom-57.5px left-93.5px"
          @click.stop="closeDialog2"
          :style="{
            backgroundImage: `url(${oss2('others/panda2023/button1.png')})`,
          }"
        ></view>
        <view class="Dialog_rule"
          >查看<span class="link" @click.stop="openRule3">活动规则</span>
        </view>
      </view>
    </view>

    <!-- 活动规则弹窗 -->
    <rule-popup
      v-if="showRule"
      @closekf="kefuShow = false"
      @openkf="openkfBtn"
      @close="closeRule"
    />

    <oreo-action-sheet
      :show="kefuShow"
      style="color: #0f2989"
      @cancel="kefuShow = false"
      cancel-text="取消"
    >
      <button class="phoneStyle" @click="PhoneCall">400-0880-325</button>
      <button open-type="contact" @click="onlineKf" class="kefu_btn">
        在线客服
      </button>
    </oreo-action-sheet>

    <!-- 活动结束弹窗 -->
    <view class="mode" v-if="showEndDialog">
      <view
        class="Dialog_body w-320px h-300px top-202px left-27px"
        :style="{
          backgroundImage: `url(${oss2('others/panda2023/panda_end.png')})`,
        }"
      >
        <view
          class="Dialog_back w-140px h-48px bottom-51px left-90px"
          @click.stop="showEndDialog = false"
          :style="{
            backgroundImage: `url(${oss2('others/panda2023/button1.png')})`,
          }"
        ></view>
      </view>
    </view>
  </scroll-view>


</template>

<script setup>
import {
  onLoad,
  onShow,
  onUnload,
  onHide,
  onShareAppMessage,
} from "@dcloudio/uni-app";
import { ref } from "vue";
import { ossImg, oss2, message } from "@/utils/utils";
import RulePopup from "./components/rule-popup.vue";
import { userLogin } from "@/services/utils";
import privacyPopup from "@/components/privacy-popup";

let enterTime = "";
let outTime = "";
let stayTime = "";

const activityStatus = ref("活动中");
const iAgree = ref(false);
const kefuShow = ref(false);

const showDialog2 = ref(false);
const showRule = ref(false);
const LuckTimes = ref(0);
const version = ref("");

const showEndDialog = ref(false);

onLoad(async (options) => {});

onShow(() => {
  // 用户进入时间
  enterTime = new Date();

  getApp().accessLogAdd();
  if (uni.getStorageSync("PANDAAGREE")) {
    iAgree.value = uni.getStorageSync("PANDAAGREE");
  }
  if (activityStatus !== "未开始") {
    uni.login({
      provider: "weixin",
      success: async (res) => {
        console.log(res);
        const loginParam = {
          type: 1,
        };
        loginParam.code = res.code;

        const { data } = await userLogin(loginParam);
        uni.setStorageSync("OPENID", data?.openId);
        uni.setStorageSync("UNIONID", data?.unionId);
        uni.setStorageSync("TOKEN", data?.accessToken);
        getApp().emdlz2("set", "user", "openid", data.openId);
        getApp().emdlz("set", "user", "unionId", data.unionId);
        getTimes(data?.unionId);
        getVersion();
        getApp().getUserInfo();
      },
    });
  }
  if (
    new Date().getTime() > 1692979199000 &&
    new Date().getTime() < 1696003200000
  ) {
    showEndDialog.value = true;
  }
  if (new Date().getTime() > 1696003200000) {
    activityStatus.value = "已结束";
  }
});

onHide(() => {
  // 用户退出时间
  outTime = new Date();
  //停留时间(毫秒)
  stayTime = (outTime?.getTime() - enterTime?.getTime()) / 1000;
  getApp().emdlz(
    "track",
    "event",
    "pandas_campaign_wish_page",
    "view",
    "campaign_landpage",
    stayTime
  );
});

onUnload(() => {
  // 用户退出时间
  outTime = new Date();
  //停留时间(毫秒)
  stayTime = (outTime?.getTime() - enterTime?.getTime()) / 1000;
  getApp().emdlz(
    "track",
    "event",
    "pandas_campaign_wish_page",
    "view",
    "campaign_landpage",
    stayTime
  );
});

const backHome = () => {
  getApp().emdlz(
    "track",
    "event",
    "pandas_campaign_page",
    "click",
    "return_oreo_app",
    ""
  );
  uni.switchTab({
    url: "/pages/home/home",
  });
};

const doAgree = () => {
  getApp().emdlz(
    "track",
    "event",
    "pandas_campaign_wish_page",
    "click",
    "agree_button",
    ""
  );
  iAgree.value = !iAgree.value;
  uni.setStorageSync("PANDAAGREE", iAgree.value);
};

const getTimes = (unionid) => {
  uni.request({
    url: `${process.env.PANDA_URL}/OreoPanda/getTodayWishTimesByUnionid`,
    method: "post",
    data: {
      unionid: unionid,
    },
    header: {
      "Content-Type": "application/x-www-form-urlencoded",
    },

    success(res) {
      console.log(res);
      if (res.data.errorcode === 0) {
        LuckTimes.value = res.data.data.times;
      } else {
        uni.showToast({
          title: res.data.errordesc,
          icon: "none",
        });
      }
    },
    fail(err) {
      uni.showToast({
        title: err,
        icon: "none",
      });
    },
  });
};

const getVersion = () => {
  uni.request({
    url: `${process.env.PANDA_URL}/OreoPanda/getVersion`,
    method: "get",
    header: {
      "Content-Type": "application/x-www-form-urlencoded",
    },

    success(res) {
      console.log(res);

      if (res.data.errorcode === 0) {
        version.value = res.data.data.version;
      } else {
        uni.showToast({
          title: res.data.errordesc,
          icon: "none",
        });
      }
    },
    fail(err) {
      uni.showToast({
        title: err,
        icon: "none",
      });
    },
  });
};

const toScanCode = () => {
  getApp().emdlz(
    "track",
    "event",
    "pandas_campaign_wish_page",
    "click",
    "start_wish_machine",
    ""
  );
  if (!iAgree.value) return message("请先同意相关协议!");
  if (LuckTimes.value === 0) return (showDialog2.value = true);
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  const pageUrl = currentPage.$page.fullPath;
  linkTo(
    `/pages/webView/webview?token=${uni.getStorageSync(
      "TOKEN"
    )}&openid=${uni.getStorageSync("OPENID")}&unionid=${uni.getStorageSync(
      "UNIONID"
    )}&memberid=${
      getApp().globalData.user.memberScore.memberId
    }&webSrc=${`${process.env.PANDA_URL}/#/pages/wish/wish`}&shareTitel=泡出童心 玩在一起&shareImg=${oss2(
      "others/panda2023/sharepic2.png"
    )}&path=${encodeURIComponent(
      pageUrl + `?from=pubid:shareback;aid:sharecard`
    )}&agree=${uni.getStorageSync("PANDAAGREE")}&version=${version.value}`
  );
};

const toPrize = () => {
  getApp().emdlz(
    "track",
    "event",
    "pandas_campaign_wish_page",
    "click",
    "divide_up_the_prize",
    ""
  );
  if (!iAgree.value) return message("请先同意相关协议!");
  // linkTo("/campaign/pages/panda2023/scanCode");
  linkTo(
    `/campaign/pages/panda2023/webview?accesstoken=${uni.getStorageSync(
      "TOKEN"
    )}&code=${"null"}&openid=${uni.getStorageSync(
      "OPENID"
    )}&unionid=${uni.getStorageSync("UNIONID")}&memberid=${
      getApp().globalData.user.memberScore.memberId
    }&agree=${uni.getStorageSync("PANDAAGREE")}`
  );
};

const toStory = () => {
  getApp().emdlz(
    "track",
    "event",
    "pandas_campaign_wish_page",
    "click",
    "jigsaw_story",
    ""
  );
  if (!iAgree.value) return message("请先同意相关协议!");
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  const pageUrl = currentPage.$page.fullPath;

  linkTo(
    `/pages/webView/webview?token=${uni.getStorageSync(
      "TOKEN"
    )}&openid=${uni.getStorageSync("OPENID")}&unionid=${uni.getStorageSync(
      "UNIONID"
    )}&memberid=${
      getApp().globalData.user.memberScore.memberId
    }&webSrc=${`${process.env.PANDA_URL}/#/pages/puzzle/puzzle`}&shareTitel=解锁奥利奥熊猫故事&shareImg=${oss2(
      "others/panda2023/sharepic1.png"
    )}&path=${encodeURIComponent(
      pageUrl + `?from=pubid:shareback;aid:sharecard`
    )}&agree=${uni.getStorageSync("PANDAAGREE")}&version=${version.value}`
  );
};

const toDesire = () => {
  getApp().emdlz(
    "track",
    "event",
    "pandas_campaign_wish_page",
    "click",
    "wish_wall",
    ""
  );

  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  const pageUrl = currentPage.$page.fullPath;
  if (!iAgree.value) return message("请先同意相关协议!");

  linkTo(
    `/pages/webView/webview?token=${uni.getStorageSync(
      "TOKEN"
    )}&openid=${uni.getStorageSync("OPENID")}&unionid=${uni.getStorageSync(
      "UNIONID"
    )}&memberid=${
      getApp().globalData.user.memberScore.memberId
    }&webSrc=${`${process.env.PANDA_URL}/#/pages/wall/wall`}&shareTitel=泡出童心 玩在一起&shareImg=${oss2(
      "others/panda2023/sharepic2.png"
    )}&path=${encodeURIComponent(
      pageUrl + `?from=pubid:shareback;aid:sharecard`
    )}&agree=${uni.getStorageSync("PANDAAGREE")}&version=${version.value}`
  );
};

const toMy = () => {
  if (!iAgree.value) return message("请先同意相关协议!");
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  const pageUrl = currentPage.$page.fullPath;
  getApp().emdlz(
    "track",
    "event",
    "pandas_campaign_wish_page",
    "click",
    "mine",
    ""
  );
  linkTo(
    `/pages/webView/webview?token=${uni.getStorageSync(
      "TOKEN"
    )}&openid=${uni.getStorageSync("OPENID")}&unionid=${uni.getStorageSync(
      "UNIONID"
    )}&memberid=${
      getApp().globalData.user.memberScore.memberId
    }&webSrc=${`${process.env.PANDA_URL}/#/pages/list/list`}&shareTitel=泡出童心 玩在一起&shareImg=${oss2(
      "others/panda2023/sharepic2.png"
    )}&path=${encodeURIComponent(
      pageUrl + `?from=pubid:shareback;aid:sharecard`
    )}&agree=${uni.getStorageSync("PANDAAGREE")}&version=${version.value}`
  );
};

const openRule = () => {
  getApp().emdlz(
    "track",
    "event",
    "pandas_campaign_wish_page",
    "click",
    "check_activity_rule_1",
    ""
  );
  showRule.value = true;
};

const openRule2 = () => {
  getApp().emdlz(
    "track",
    "event",
    "pandas_campaign_wish_page",
    "click",
    "check_activity_rule_2",
    ""
  );
  showRule.value = true;
};

const closeDialog2 = () => {
  showDialog2.value = false;
  getApp().emdlz(
    "track",
    "event",
    "pandas_campaign_wish_page",
    "click",
    "pop-up_return",
    ""
  );
};

const openRule3 = () => {
  getApp().emdlz(
    "track",
    "event",
    "pandas_campaign_wish_page",
    "click",
    "check_activity_rule_3",
    ""
  );
  showRule.value = true;
};

const closeRule = () => {
  getApp().emdlz(
    "track",
    "event",
    "pandas_campaign_wish_rule_page",
    "click",
    "shut_down",
    ""
  );
  showRule.value = false;
};

const openkfBtn = () => {
  getApp().emdlz(
    "track",
    "event",
    "pandas_campaign_wish_rule_page",
    "click",
    "contact_customer_service",
    ""
  );
  kefuShow.value = true;
};

const PhoneCall = () => {
  getApp().emdlz(
    "track",
    "event",
    "pandas_campaign_wish_rule_page",
    "click",
    "contact_customer_service_phone",
    ""
  );
  uni.makePhoneCall({
    phoneNumber: "400-0880-325",
  });
};

const onlineKf = () => {
  getApp().emdlz(
    "track",
    "event",
    "pandas_campaign_wish_rule_page",
    "click",
    "contact_customer_service_online",
    ""
  );
};

const linkTo = (url) => uni.navigateTo({ url });

const linkToWebView = (url) => {
  linkTo(
    `/pages/webView/webview?token=${uni.getStorageSync(
      "TOKEN"
    )}&openid=${uni.getStorageSync("OPENID")}&unionid=${uni.getStorageSync(
      "UNIONID"
    )}&memberid=${
      getApp().globalData.user.memberScore.memberId
    }&webSrc=${url}&agree=${uni.getStorageSync("PANDAAGREE")}&version=${
      version.value
    }`
  );
};

onShareAppMessage((e) => {
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  console.log(currentPage);
  const pageUrl = currentPage.$page.fullPath;

  const shareObj = {
    title: "泡出童心 玩在一起", // 默认是小程序的名称(可以写slogan等)
    path: pageUrl + `?from=pubid:shareback;aid:sharecard`, // 默认是当前页面，必须是以‘/’开头的完整路径
    imageUrl: oss2("others/panda2023/sharepic2.png"), //自定义图片路径，可以是本地文件路径、代码包文件路径或者网络图片路径，支持PNG及JPG，不传入 imageUrl 则使用默认截图。显示图片长宽比是 5:4
    success: (res) => {
      // 转发成功之后的回调
      if (res.errMsg == "shareAppMessage:ok") {
      }
    },
    fail: (err) => {
      // 转发失败之后的回调
      console.log("转发失败之后的回调", err);
      if (res.errMsg == "shareAppMessage:fail cancel") {
        // 用户取消转发
        console.log("用户取消转发");
      } else if (res.errMsg == "shareAppMessage:fail") {
        // 转发失败，其中 detail message 为详细失败信息
        console.log("转发失败，其中detail message 为详细失败信息");
      }
    },
    complete: () => {
      // 转发结束之后的回调（转发成不成功都会执行）
      console.log("转发结束之后的回调（转发成不成功都会执行）");
    },
  };
  console.log(shareObj);
  return shareObj;
});
</script>

<style>
page {
  background-color: #1335b4 !important;
}
</style>
<style lang="less" scoped>
@import "@/static/css/theme.less";

.puzzle {
  height: 1448rpx !important;
}
.panda-container {
  width: 375px;
  background-color: #1335b3;
  height: 728px;
  background-repeat: no-repeat;
  background-position: top left;
  background-size: 375px 100%;
  position: relative;

  .rule {
    position: absolute;
    width: 97px;
    height: 32px;
    right: 0;
    top: 18.5px;
    background-repeat: no-repeat;
    background-position: top left;
    background-size: 97px 100%;
  }
  .desire {
    position: absolute;
    width: 81px;
    height: 32px;
    right: 0;
    top: 52.5px;
    background-repeat: no-repeat;
    background-position: top left;
    background-size: 81px 100%;
  }

  .my {
    position: absolute;
    width: 94px;
    height: 32px;
    left: 0;
    top: 18.5px;
    background-repeat: no-repeat;
    background-position: top left;
    background-size: 94px 100%;
  }
  .wishGranter {
    position: absolute;
    width: 175px;
    height: 48.5px;
    top: 432.5px;
    left: 105px;
    background-repeat: no-repeat;
    background-position: top left;
    background-size: 165px 100%;
    z-index: 10;
  }
  .prize_and_story {
    position: absolute;
    display: flex;
    top: 444px;
    justify-content: space-around;
    width: 100%;
    .prize {
      position: relative;
      width: 160px;
      height: 180px;
      background-repeat: no-repeat;
      background-position: top left;
      background-size: 160px 100%;
      .prize_btn {
        position: absolute;
        top: 142px;
        left: 19.5px;
        width: 125px;
        height: 40.5px;
        background-repeat: no-repeat;
        background-position: top left;
        background-size: 125px 100%;
      }
    }
    .story {
      position: relative;
      width: 160px;
      height: 180px;
      background-repeat: no-repeat;
      background-position: top left;
      background-size: 160px 100%;
      .story_btn {
        position: absolute;
        top: 142px;
        left: 11.5px;
        width: 125px;
        height: 40.5px;
        background-repeat: no-repeat;
        background-position: top left;
        background-size: 125px 100%;
      }
    }
  }
  .backHomeBtn {
    position: absolute;
    width: 220px;
    height: 54px;
    background-repeat: no-repeat;
    background-position: top left;
    background-size: 220px 100%;
    top: 518px;
    left: 155rpx;
  }

  .agree {
    font-size: 12px;
    color: #ffffff;
    box-sizing: border-box;
    z-index: 10;
    position: absolute;
    top: 638.5px;
    width: 100%;
    left: 0;

    .agree-content {
      word-break: break-all;
    }

    .link {
      color: #6ed4ff;
      display: inline-block;
      text-decoration: underline;
    }

    .i-agree {
      width: 12px;
      height: 12px;
      margin-right: 4px;
      background-color: #ffffff;
      box-sizing: border-box;
    }
  }
}

.mode {
  width: 100%;
  height: 100vh;
  position: fixed;
  top: 0;
  left: 0;
  z-index: 90;
  background-color: rgba(10, 28, 108, 0.8);
  .Dialog_body {
    position: absolute;
    background-repeat: no-repeat;
    background-position: top left;
    background-size: 100% 100%;
    .Dialog_back {
      position: absolute;
      background-repeat: no-repeat;
      background-position: top left;
      background-size: 100% 100%;
    }
    .Dialog_rule {
      width: 100%;
      text-align: center;
      font-size: 12.5px;
      position: absolute;
      bottom: 22px;
      color: #0f2989;
      .link {
        color: #30a8fb;
        text-decoration: underline;
        margin-left: 5px;
      }
    }
  }

  .rule-content {
    position: absolute;
    width: 310px;
    height: 478px;
    top: 119.5px;
    left: 32.5px;
    background-repeat: no-repeat;
    background-position: top left;
    background-size: 310px 100%;
    .rule_close {
      position: absolute;
      right: 13px;
      top: 20px;
      width: 30px;
      height: 30px;
      background-repeat: no-repeat;
      background-position: top left;
      background-size: 30px 100%;
    }
    .rule_text {
      width: 231px;
      height: 303.5px;
      margin: 0 auto;
      margin-top: 71px;
      overflow-y: auto;
      font-size: 10px;
      color: #0353cb;
    }
    .rule_kefu {
      width: 193px;
      height: 53px;
      margin: 0 auto;
      margin-top: 25.5px;
      background-repeat: no-repeat;
      background-position: top left;
      background-size: 193px 100%;
    }
  }
}

:deep(.van-action-sheet__gap) {
  height: auto;
}

:deep(.van-action-sheet__cancel) {
  padding: 0 !important;
  font-size: 12px;
  color: #0f2989;
  line-height: 36px !important;
}

.phoneStyle {
  font-size: 12px;
  color: #2c82d0;
  width: 343.5px;
  padding: 0 !important;
  line-height: 36px !important;
  margin: 0 auto !important;
  border-radius: 0 !important;
  background: none !important;
  border-bottom: solid 1px #eaeaea;
  &::after {
    border: none;
  }
}
.kefu_btn {
  font-size: 12px;
  color: #0f2989;
  width: 343.5px;
  line-height: 36px !important;
  margin: 0 auto !important;
  padding: 0 !important;
  border-radius: 0 !important;
  background: none !important;
  border-bottom: solid 1px #eaeaea;
  &::after {
    border: none;
  }
}
</style>
